﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Barry.Model;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;

namespace Barry.Repository
{
  public  class NHibernateHelper
    {

       
        public static ISessionFactory CreateSessionFactory()
        {
            return Fluently.Configure()
                           .Database(MsSqlConfiguration.MsSql2008.ConnectionString(
                               c => c.Server("127.0.0.1")
                               .Database("TestFluentNhibernate")
                               .Username("sa")
                               .Password("Password01!")))
                           .Mappings(m => m.FluentMappings.AddFromAssemblyOf<NewsMap>())
                           .ExposeConfiguration(CreateSchema)
                           .BuildSessionFactory();
        }

      private static void CreateSchema(Configuration cfg)
      {
          var schemaExport = new SchemaExport(cfg);
          schemaExport.SetOutputFile("c:\\abc\\abc.sql");
          schemaExport.Create(false, true);
      }


      private static ISession _session;

      public static ISession OpenSession()
      {
          if (_session == null)
          {
              var sessionFactory = CreateSessionFactory();
              _session = sessionFactory.OpenSession();
              return _session;
          }
          return _session;
      }
    }
}
